package com.irdstudio.apicenter.console.controller.appframe;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.irdstudio.apicenter.console.controller.MacmsBaseAction;
import com.irdstudio.apicenter.console.dm.AppFrameModule;
import com.irdstudio.apicenter.console.dm.module.ModuleEntity;
import com.irdstudio.apicenter.console.dm.module.ModuleService;
import com.irdstudio.apicenter.console.dm.util.FootPage;
import com.irdstudio.apicenter.console.dm.util.FootPageDao;
import com.irdstudio.apicenter.console.service.appframe.AppFrameModuleService;
import com.irdstudio.apicenter.console.startup.MacmsRoot;
import com.irdstudio.apicenter.console.util.CurrentDateUtil;
import com.irdstudio.apicenter.core.dvo.RspValue;
import com.irdstudio.apicenter.frame.core.jdbc.JdbcBaseDAO;
import com.irdstudio.apicenter.frame.core.jdbc.container.PageInfo;
import com.irdstudio.apicenter.frame.core.jdbc.tablemodel.ITableModelDAO;
import com.irdstudio.apicenter.frame.service.ModuleGenerateService;
import com.irdstudio.apicenter.frame.util.BeanUtils;
import com.opensymphony.xwork2.ActionChainResult;
import com.opensymphony.xwork2.ActionContext;

/**
 * 平台模块管理
 * 
 * @author jr
 * 
 */
@Controller
@RequestMapping(value = "/appFrameModule1")
public class AppFrameModuleAction1 extends MacmsBaseAction {

	@Autowired
	private AppFrameModuleService appFrameModuleService;

	@Autowired
	private ModuleGenerateService moduleGenerateService;
	
	@Autowired
	private ModuleService moduleService;

	@RequestMapping(value = "appFrameModuleList1")
	public ModelAndView appFrameModuleList1(HttpServletRequest request)
			throws Exception {
		/*
		 * ModelAndView modelAndView = new ModelAndView(); List<AppFrameModule>
		 * appFrameModuleList =
		 * appFrameModuleService.queryAppFrameModuleList("", "");
		 * modelAndView.addObject("AppFrameModuleList", appFrameModuleList);
		 * modelAndView.setViewName("appframe/module"); return modelAndView;
		 */
		// 获取页码和条数service

		String appid = request.getParameter("appid");
		String appname = "";
		if(request.getParameter("appname") != null){
			appname = new String(request
					.getParameter("appname").getBytes("iso-8859-1"), "UTF-8");
		}
		int row = 0;
		int size = 0;
		row = (null == request.getParameter("pageNo") ? 0 : Integer
				.parseInt(request.getParameter("pageNo")));
		size = (null == request.getParameter("pageSize") ? 0 : Integer
				.parseInt(request.getParameter("pageSize")));

		// size=Integer.parseInt(request.getParameter("pageSize"));
		// 获取分页信息
		FootPageDao fpd = new FootPageDao();
		FootPage fp = new FootPage();
		fp = fpd
				.querypage(
						"  app_frame_module a, s_module_base b  where   a.module_id = b.module_id  and  a.app_id= '"
								+ appid + "'", row, size);

		// 获取分页的起始编号
		row = (fp.getPageNo() - 1) * fp.getPageSize();
		String conditionSql = "where  a.module_id = b.module_id  and  APP_ID='"
				+ appid + "'";
		List<HashMap<String, String>> Modulelist = appFrameModuleService
				.queryByAppid1(conditionSql);

		ModelAndView modelAndView = new ModelAndView();
		//modelAndView.addObject("Modulelist", Modulelist);
		// List<AppFrameModule> appFrameModuleList =
		// appFrameModuleService.queryAppFrameModuleList("", "",conditionSql);
		modelAndView.addObject("appid", appid);
		modelAndView.addObject("appname", appname);
		modelAndView.addObject("Modulelist", Modulelist);
		modelAndView.addObject("page", fp);
		modelAndView.setViewName("appframe/module");
		return modelAndView;
	}
	
	@RequestMapping(value = "appModuleIndex")
	public String appModuleIndex(HttpServletRequest request) throws Exception {

		// 取得传入应用标识
		String appId = request.getParameter("appid");
		if (StringUtils.isEmpty(appId)) {
			throw new Exception("必须传入应用标识(appid)参数!");
		}
		// 取得传入应用名称
		//Windows转码方式
		String appName = "";
		if(request.getParameter("appname") != null){
			appName = new String(request
					.getParameter("appname").getBytes("iso-8859-1"), "UTF-8");
		}
		//Linux转码方式
		/*String appName = java.net.URLDecoder.decode(request
				.getParameter("appname"), "UTF-8");*/
	    if (StringUtils.isEmpty(appName)) {
			throw new Exception("必须传入应用名称(appName)参数!");
		}
	    List<AppFrameModule> list = appFrameModuleService.queryAllByAppId(appId);
	    Map<AppFrameModule, List<AppFrameModule>> map = new HashMap<AppFrameModule, List<AppFrameModule>>();
	    if(list != null && list.size() > 0){
	    	for(AppFrameModule module : list){
	    		List<AppFrameModule> sonModule = appFrameModuleService
	    				.queryAppFrameModuleByParentId(appId, module.getModuleId());
	    		if(sonModule !=null && sonModule.size() > 0){
	    			map.put(module, sonModule);
	    		}else{
	    			map.put(module, null);
	    		}
	    	}
	    }
	    request.setAttribute("moudlemap", map);
		request.setAttribute("appid", appId);
		request.setAttribute("appname", appName);
		return "make/appModuleIndex";
	}	

	/**
	 * 生成应用的模块代码
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "generateModuleCode")
	public void generateModuleCode(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String modules = request.getParameter("modules");
		String appId = request.getParameter("appId");
		if (StringUtils.isEmpty(appId)) {
			this.renderJsonData(response, new RspValue("未接收到应用编号(appId)参数!"));
		}
		if (StringUtils.isEmpty(modules)) {
			this.renderJsonData(response, new RspValue("未接收到模块编号(modules)参数!"));
		}
		
		String filepath = MacmsRoot.getMacmsPathService()
				.getMacmsWorkspacePath().concat("/appprj/").concat(appId).concat("/");
		File file = new File(filepath);
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
			// 首次，则从SVN上checkout工程下来
			MacmsRoot.getSvnProjectService().checkoutProject(appId);
		} else {
			// 后续则从SVN上更新工程
			MacmsRoot.getSvnProjectService().updateProject(appId);
		}

		// 分解得到模块编号并为其生成模块代码
		String[] moduleArray = modules.split(",");
		String emInfo = "";
		for (int i = 0; i < moduleArray.length; i++) {
			// 生成模块的代码
			RspValue rspValue = moduleGenerateService.generateModuleCode(appId,
					moduleArray[i]);
			if (rspValue == null || !rspValue.isOK()) {
				emInfo += rspValue.getEm() + "|";
			}
		}

		// 如果没有错误信息返回，则返回成功，否则返回组合后的失败信息
		if (!StringUtils.isEmpty(emInfo)) {
			this.renderJsonData(response, new RspValue(emInfo));
		} else {
			this.renderJsonData(response, new RspValue());
		}
	}

	/**
	 * ajax请求不需要返回页面，只需要得到response中的数据即可，所以方法签名为void即可
	 * 
	 * @param request
	 * @param response
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	@RequestMapping(value = "ajax", method = RequestMethod.POST)
	public void deleteAjaxDatas(HttpServletRequest request,
			HttpServletResponse response) throws ClassNotFoundException,
			SQLException {
		String jsonResult = deleteAppFrameModule(request);
		renderJsonData(response, jsonResult);
	}

	private String deleteAppFrameModule(HttpServletRequest request)
			throws ClassNotFoundException, SQLException {
		String id = request.getParameter("appid");
		String midStr = request.getParameter("moduleid");
		String mList[] = midStr.split(",");
		int flag = -1;
		for (int i = 0; i < mList.length; i++) {
			flag = appFrameModuleService.deleteAppFrameModule(id, mList[i]);
		}
		Map<String, Object> map = new HashMap<String, Object>(1);
		map.put("flag", flag);
		String jsonResult = JSON.toJSONString(map);
		return jsonResult;
	}

	/**
	 * 应用交易配置入口
	 * 
	 * @param request
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "appFrameTradeMain")
	public String appFrameTrade(HttpServletRequest request,
			@RequestParam(value = "appid", required = true) String id)
			throws Exception {

		// 获取所有参数
		super.getAllRequestData(request);

		// 取得传入模板标识
		String appId = super.context.getRequestParams().getValue("appid");
		if (StringUtils.isEmpty(appId)) {
			throw new Exception("必须传入应用标识(appid)参数!");
		}

		request.setAttribute("appid", appId);
		return "appframe/appTradeMain";
	}

	/**
	 * 应用后台交易列表
	 * 
	 * @param request
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "appFrameTradeList")
	public String appFrameTradeList(HttpServletRequest request,
			@RequestParam(value = "appid", required = true) String id)
			throws Exception {
		String qtcode = "";
		String qtname = "";
		if (request.getParameter("qtcode") != null) {
			qtcode = request.getParameter("qtcode");
		}
		if (request.getParameter("qtname") != null) {
			qtname = request.getParameter("qtname");
		}

		// 将查询条件放到上下文中
		request.setAttribute("qtcode", qtcode);
		request.setAttribute("qtname", qtname);

		// 取得传入模板标识
		String appId = super.context.getRequestParams().getValue("appid");
		if (StringUtils.isEmpty(appId)) {
			throw new Exception("必须传入应用标识(appid)参数!");
		}

		// 获取所有参数
		super.getAllRequestData(request);

		// 查询数据并放入到上下文中
		String sql = "select * from app_trade_private where app_id=?  and  trade_code  like  '%"
				+ qtcode + "%'  and  trade_name like '%" + qtname + "%' ";
		PageInfo pageInfo = this.getPageInfo();
		ITableModelDAO dao = (ITableModelDAO) BeanUtils
				.getBean("tableModelDAO");
		context.addDataList("atpList", dao.queryList(sql, pageInfo,
				new Object[] { appId }));
		context.addPageInfo("atpList", pageInfo);
		request.setAttribute("appid", appId);

		// 将数据上下文放到属性中
		request.setAttribute("context", super.context);
		return "appframe/appTradeList";
	}

	/**
	 * 应用后台交易列表
	 * 
	 * @param request
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "appFrameFc")
	public String appFrameFc(HttpServletRequest request,
			@RequestParam(value = "appid", required = true) String id)
			throws Exception {

		// 获取所有参数
		super.getAllRequestData(request);

		// 取得传入模板标识
		String appId = super.context.getRequestParams().getValue("appid");
		if (StringUtils.isEmpty(appId)) {
			throw new Exception("必须传入应用标识(appid)参数!");
		}

		// 查询数据并放入到上下文中
		String sql = "select * from app_channel_forward where app_id=?";
		PageInfo pageInfo = this.getPageInfo();
		context.addDataList("acfList", this.getTableModelDAO().queryList(sql,
				pageInfo, new Object[] { appId }));
		context.addPageInfo("acfList", pageInfo);
		request.setAttribute("appid", appId);

		// 将数据上下文放到属性中
		request.setAttribute("context", super.context);
		return "appframe/appTradeChannel";
	}

	/**
	 * APP资源设置
	 * 
	 * @param request
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "appFrameResource")
	public String appFrameResource(HttpServletRequest request,
			@RequestParam(value = "appid", required = true) String id)
			throws Exception {

		// 获取所有参数
		super.getAllRequestData(request);

		// 取得传入模板标识
		String appId = super.context.getRequestParams().getValue("appid");
		if (StringUtils.isEmpty(appId)) {
			throw new Exception("必须传入应用标识(appid)参数!");
		}

		// 查询数据并放入到上下文中
		String sql = "select * from app_resource where app_id=?";
		PageInfo pageInfo = this.getPageInfo();
		context.addDataList("arList", this.getTableModelDAO().queryList(sql,
				pageInfo, new Object[] { appId }));
		context.addPageInfo("arList", pageInfo);

		// 将数据上下文放到属性中
		request.setAttribute("context", super.context);
		return "appframe/appResource";

	}
	
	/**
	 * 生成页面的代码
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "generatePageCode")
	public void generatePageCode(HttpServletRequest request,
			HttpServletResponse response){
		
		String pageId = request.getParameter("pageId");
		String appId = (String) request.getSession().getAttribute("appid");
		if (StringUtils.isEmpty(pageId)) {
			this.renderJsonData(response, new RspValue("未接收到页面标识(pageId)参数!"));
		}
		System.out.println("开始生成页面...");
		String filepath = MacmsRoot.getMacmsPathService()
				.getMacmsWorkspacePath().concat("/appprj/").concat(appId).concat("/");
		File file = new File(filepath);
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
			// 首次，则从SVN上checkout工程下来
			System.out.println("从SVN上checkout工程...");
			MacmsRoot.getSvnProjectService().checkoutProject(appId);
		} else {
			// 后续则从SVN上更新工程
			System.out.println("从SVN上更新工程...");
			MacmsRoot.getSvnProjectService().updateProject(appId);
		}	
		// 生成模块的代码
		RspValue rspValue = null;
		try {
			rspValue = moduleGenerateService.generatePageCode(appId, pageId);
		} catch (IOException e) {
			System.out.println("代码生成异常:"+e.getMessage());
			rspValue = new RspValue("代码生成异常:"+e.getMessage());
		}
		String emInfo = rspValue.getEm();
		// 如果没有错误信息返回，则返回成功，否则返回组合后的失败信息
		if (!StringUtils.isEmpty(emInfo)) {
			this.renderJsonData(response, rspValue);
		} else {
			this.renderJsonData(response, rspValue);
		}
	}
	
	/**
	 * 保存页面数据
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "savePageRequest")
	public void savePageRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		String pageId = request.getParameter("pageId");
		String pageName = request.getParameter("pageName");
		if (StringUtils.isEmpty(pageId)) {
			this.renderJsonData(response, new RspValue("未接收到页面标识(pageId)参数!"));
		}
		if (StringUtils.isEmpty(request.getParameter("pageName"))) {
			this.renderJsonData(response, new RspValue("页面名称(pageName)为空!"));
		}
		//修改页面
		String sql = "update s_page_base set page_name=? where page_id=? ";
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		int flag = baseDao.update(sql, pageName, pageId);
		// 如果没有错误信息返回，则返回成功，否则返回组合后的失败信息
		if (flag > 0) {
			this.renderJsonData(response, new RspValue("修改成功!"));
		} else {
			this.renderJsonData(response, new RspValue("修改失败!"));
		}
	}
	
	/**
	 * 创建子模块
	 * 
	 * @param request
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "createSonModule")
	public String createSonModule(HttpServletRequest request)
			throws Exception {

		// 获取所有参数
		String appId = request.getParameter("appid");
		if (StringUtils.isEmpty(appId)) {
			throw new Exception("传入应用标识(appid)参数!");
		}
		String moduleid = request.getParameter("moduleid");
		//String appName = request.getParameter("appname");
		String appName = new String(request
				.getParameter("appname").getBytes("iso-8859-1"), "UTF-8");
		/*String mList[] = midStr.split(",");
		int flag = -1;
		for (int i = 0; i < mList.length; i++) {
			flag = appFrameModuleService.deleteAppFrameModule(id, mList[i]);
		}*/
		// 将数据上下文放到属性中
		request.setAttribute("moduleid", moduleid);
		request.setAttribute("appid", appId);
		request.setAttribute("appname", appName);
		return "admin/sonModuleCreate";

	}
	
	/*
	 * 新增模块
	 */
	@RequestMapping(value = "addModule")
	public @ResponseBody
	ModelAndView addModule(HttpServletRequest request, ModuleEntity meoduleEntity)
			throws SQLException, ClassNotFoundException {
		ModelAndView modelAndView = new ModelAndView();
		String sql = "insert into s_module_base(module_id,module_name,module_index_page_id,last_modify_date) values (?,?,?,?)";
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		int bl = baseDao.update(sql, meoduleEntity.getModule_id(),
				meoduleEntity.getModule_name(), meoduleEntity
						.getModule_index_page_id(), CurrentDateUtil
						.getTodayDate());
		AppFrameModule appModule = new AppFrameModule();
		appModule.setAppId(meoduleEntity.getParam_code());
		appModule.setModuleId(meoduleEntity.getModule_id());
		appModule.setParentModuleId(meoduleEntity.getParam_name() == null ? null : meoduleEntity.getParam_name().split(",")[0]);
		int rs = appFrameModuleService.insertFrameModule(appModule);
		System.out.println(meoduleEntity.getModule_id()+"--"+meoduleEntity.getModule_name()+"--"
						+meoduleEntity.getModule_index_page_id()+"--"+meoduleEntity.getParam_code()+"--"
				+meoduleEntity.getParam_name()+"---"+meoduleEntity.getParam_remarks());
		if(bl >0 && rs >0){
			modelAndView.addObject("addflag", "1");
			modelAndView.addObject("appid", meoduleEntity.getParam_code());
			modelAndView.addObject("appname", meoduleEntity.getParam_remarks());
		}else{
			modelAndView.addObject("addflag", "0");
		}
		return modelAndView;
	}

}
